package com.cn.wanxi.util;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class Fileter implements Filter {
    /**
     * 设置谁可以访问后台代码
     *
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        0.乱码设置

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        request.setCharacterEncoding("UTF-8");//请求
        response.setCharacterEncoding("UTF-8");//响应
        String path = request.getServletPath();
//        System.out.println(path);
        boolean fangxin = false;
        String paths[] = {"/back/login.jsp", "/code", "/login", "/home", "/company", "/news", "/product", "/callus", "/online"};
        for (int i = 0; i < paths.length; i++) {
            if (path.equals(paths[i])) {
                fangxin = true;
                break;
            }
        }
        if (fangxin) {
            filterChain.doFilter(servletRequest, servletResponse);//放行的意思
        }
//        判断用户是否登錄，如果已经登陆，则放行，否则，进入登陆页面进行登陆
//        需要在session裏面去判斷是否已经登陆
        String username = (String) request.getSession().getAttribute("username");
        if (username == null) {
            request.getRequestDispatcher("/back/login.jsp").forward(request, servletResponse);
        } else {
            filterChain.doFilter(servletRequest, servletResponse);//放行的意思
        }
    }
}
